"""导出视图模块"""
from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel,
                             QPushButton, QComboBox, QSpinBox, QCheckBox,
                             QGroupBox, QLineEdit, QFileDialog, QMessageBox,
                             QProgressBar)
from PyQt6.QtCore import Qt, QThread, pyqtSignal
from src.ui.styles import (BUTTON_STYLE, INPUT_STYLE, LABEL_STYLE,
                      PROGRESS_BAR_STYLE, MESSAGEBOX_STYLE, COMBO_BOX_STYLE)
from src.video_processor import VideoProcessor, SceneInfo
import os

class ExportWorker(QThread):
    progress_updated = pyqtSignal(int)
    export_finished = pyqtSignal(str)
    error_occurred = pyqtSignal(str)
    
    def __init__(self, video_path, scenes, output_path):
        super().__init__()
        self.video_path = video_path
        self.scenes = scenes
        self.output_path = output_path
        
    def run(self):
        try:
            processor = VideoProcessor()
            processor.load_video(self.video_path)
            
            # 根据输出路径的扩展名确定导出格式
            ext = os.path.splitext(self.output_path)[1].lower()
            
            if ext == '.draft':
                # 导出剪映草稿
                self._export_draft(processor)
            elif ext == '.zip':
                # 导出分镜图片
                self._export_images(processor)
            elif ext == '.json':
                # 导出场景列表
                self._export_json(processor)
            elif ext == '.mp4':
                # 导出视频片段
                self._export_video(processor)
            else:
                raise ValueError(f"不支持的导出格式：{ext}")
                
            self.export_finished.emit(self.output_path)
            
        except Exception as e:
            self.error_occurred.emit(str(e))
            
    def _export_draft(self, processor):
        """导出剪映草稿"""
        # 创建导出目录
        export_dir = os.path.splitext(self.output_path)[0]
        os.makedirs(export_dir, exist_ok=True)
        
        # 导出视频片段
        medias_dir = os.path.join(export_dir, "medias")
        os.makedirs(medias_dir, exist_ok=True)
        processor.export_scene_videos(self.scenes, medias_dir)
        
        # 生成 project.json
        materials = []
        timeline = []
        start_time = 0.0
        for i, scene in enumerate(self.scenes):
            material_id = f"scene_{scene.index:03d}"
            rel_path = f"medias/scene_{scene.index:03d}.mp4"
            materials.append({"id": material_id, "path": rel_path})
            timeline.append({
                "material_id": material_id,
                "start": start_time,
                "duration": scene.duration
            })
            start_time += scene.duration
            
        project_json = {
            "materials": materials,
            "timeline": timeline
        }
        
        import json
        with open(os.path.join(export_dir, "project.json"), "w", encoding="utf-8") as f:
            json.dump(project_json, f, ensure_ascii=False, indent=2)
            
    def _export_images(self, processor):
        """导出分镜图片"""
        import zipfile
        with zipfile.ZipFile(self.output_path, 'w') as zipf:
            for i, scene in enumerate(self.scenes):
                # 导出场景预览图
                image_path = processor.export_scene_image(scene, os.path.dirname(self.output_path))
                if image_path:
                    zipf.write(image_path, os.path.basename(image_path))
                    os.remove(image_path)  # 删除临时文件
                    
    def _export_json(self, processor):
        """导出场景列表"""
        scenes_data = []
        for scene in self.scenes:
            scene_dict = {
                "index": scene.index,
                "start_time": scene.start_time,
                "end_time": scene.end_time,
                "duration": scene.duration,
                "description": scene.description
            }
            scenes_data.append(scene_dict)
            
        import json
        with open(self.output_path, "w", encoding="utf-8") as f:
            json.dump(scenes_data, f, ensure_ascii=False, indent=2)
            
    def _export_video(self, processor):
        """导出视频片段"""
        processor.export_scene_videos(self.scenes, os.path.dirname(self.output_path))

class ExportView(QWidget):
    """导出视图类（喜马拉雅美化）"""
    export_started = pyqtSignal(dict)
    export_finished = pyqtSignal(str)
    back_requested = pyqtSignal()  # 新增返回信号

    def __init__(self):
        super().__init__()
        self.setWindowTitle("导出设置")
        self.scenes = []
        self.video_path = None
        self._init_ui()
        self._apply_styles()

    def _init_ui(self):
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(24, 24, 24, 24)
        main_layout.setSpacing(24)
        self._create_format_group(main_layout)
        self._create_options_group(main_layout)
        self._create_path_group(main_layout)
        self._create_progress_bar(main_layout)
        self._create_bottom_buttons(main_layout)
        # 终极兜底：只用delegate控制高度，QSS只控制颜色
        from PyQt6.QtWidgets import QListView, QStyledItemDelegate
        class FixedHeightDelegate(QStyledItemDelegate):
            def sizeHint(self, option, index):
                size = super().sizeHint(option, index)
                size.setHeight(36)
                return size
        view = QListView()
        view.setSpacing(0)
        view.setStyleSheet("QListView { background: #fff; color: #222; font-size: 15px; }")
        view.setItemDelegate(FixedHeightDelegate(view))
        self.quality_combo.setView(view)

    def _create_format_group(self, parent_layout):
        group = QGroupBox("导出格式")
        group_layout = QVBoxLayout(group)
        group_layout.setContentsMargins(18, 18, 18, 18)
        group_layout.setSpacing(18)
        format_layout = QHBoxLayout()
        format_label = QLabel("选择格式:")
        self.format_combo = QComboBox()
        self.format_combo.addItems(["剪映草稿（.draft）"])
        format_layout.addWidget(format_label)
        format_layout.addWidget(self.format_combo)
        format_layout.addStretch()
        group_layout.addLayout(format_layout)
        parent_layout.addWidget(group)

    def _create_options_group(self, parent_layout):
        group = QGroupBox("导出选项")
        group_layout = QVBoxLayout(group)
        group_layout.setContentsMargins(18, 18, 18, 18)
        group_layout.setSpacing(18)
        self.include_preview_check = QCheckBox("包含场景预览图")
        self.include_preview_check.setChecked(True)
        self.include_metadata_check = QCheckBox("包含场景元数据")
        self.include_metadata_check.setChecked(True)
        self.include_timeline_check = QCheckBox("包含时间轴信息")
        self.include_timeline_check.setChecked(True)
        group_layout.addWidget(self.include_preview_check)
        group_layout.addWidget(self.include_metadata_check)
        group_layout.addWidget(self.include_timeline_check)
        quality_layout = QHBoxLayout()
        quality_label = QLabel("视频质量:")
        self.quality_combo = QComboBox()
        self.quality_combo.addItems([
            "原始质量", "高质量 (1080p)", "中等质量 (720p)", "低质量 (480p)"
        ])
        quality_layout.addWidget(quality_label)
        quality_layout.addWidget(self.quality_combo)
        quality_layout.addStretch()
        group_layout.addLayout(quality_layout)
        parent_layout.addWidget(group)

    def _create_path_group(self, parent_layout):
        group = QGroupBox("导出路径")
        group_layout = QVBoxLayout(group)
        group_layout.setContentsMargins(18, 18, 18, 18)
        group_layout.setSpacing(18)
        path_layout = QHBoxLayout()
        self.path_edit = QLineEdit()
        self.path_edit.setPlaceholderText("选择导出路径...")
        browse_btn = QPushButton("浏览")
        browse_btn.clicked.connect(self._browse_path)
        path_layout.addWidget(self.path_edit)
        path_layout.addWidget(browse_btn)
        group_layout.addLayout(path_layout)
        parent_layout.addWidget(group)

    def _create_progress_bar(self, parent_layout):
        self.progress_bar = QProgressBar()
        self.progress_bar.setVisible(False)
        parent_layout.addWidget(self.progress_bar)

    def _create_bottom_buttons(self, parent_layout):
        button_layout = QHBoxLayout()
        button_layout.setContentsMargins(0, 0, 0, 0)
        button_layout.setSpacing(10)
        # 左下角返回
        self.back_btn = QPushButton("返回")
        self.back_btn.clicked.connect(self.back_requested.emit)
        button_layout.addWidget(self.back_btn)
        button_layout.addStretch()
        # 右下角导出
        self.export_btn = QPushButton("开始导出")
        self.export_btn.clicked.connect(self._start_export)
        self.export_btn.setEnabled(False)
        button_layout.addWidget(self.export_btn)
        parent_layout.addLayout(button_layout)

    def _apply_styles(self):
        XM_PRIMARY = "#FF6A00"
        XM_PRIMARY_DARK = "#FF8C1A"
        XM_BG = "#F7F8FA"
        XM_CARD = "#FFFFFF"
        XM_TEXT = "#222222"
        XM_TEXT_SECONDARY = "#666666"
        XM_DIVIDER = "#EDEDED"
        self.setStyleSheet(f"""
            QWidget {{
                background-color: {XM_BG};
            }}
            {COMBO_BOX_STYLE}
            QGroupBox {{
                background: {XM_CARD};
                border-radius: 14px;
                border: 1.5px solid {XM_DIVIDER};
                margin-top: 1.2em;
                font-weight: bold;
                font-size: 16px;
                color: {XM_PRIMARY};
                padding-top: 8px;
            }}
            QGroupBox::title {{
                subcontrol-origin: margin;
                subcontrol-position: top left;
                left: 12px;
                top: 8px;
                padding: 0 6px;
                background: transparent;
            }}
            QLabel {{
                color: {XM_TEXT};
                font-size: 15px;
            }}
            QLineEdit {{
                background: #fff;
                border: 1.5px solid {XM_DIVIDER};
                border-radius: 8px;
                padding: 8px 12px;
                font-size: 15px;
                color: {XM_TEXT};
            }}
            QCheckBox {{
                color: {XM_TEXT_SECONDARY};
                font-size: 15px;
                spacing: 8px;
            }}
            QCheckBox::indicator {{
                width: 20px;
                height: 20px;
                border-radius: 4px;
                border: 1.5px solid {XM_DIVIDER};
                background: #fff;
            }}
            QCheckBox::indicator:checked {{
                background: {XM_PRIMARY};
                border: 1.5px solid {XM_PRIMARY};
            }}
            QPushButton {{
                background-color: {XM_PRIMARY};
                color: #fff;
                border: none;
                border-radius: 8px;
                padding: 10px 32px;
                font-size: 16px;
                font-weight: 500;
            }}
            QPushButton:hover {{
                background-color: {XM_PRIMARY_DARK};
            }}
            QProgressBar {{
                border: 1.5px solid {XM_DIVIDER};
                border-radius: 8px;
                background: #fff;
                height: 18px;
            }}
            QProgressBar::chunk {{
                background: {XM_PRIMARY};
                border-radius: 8px;
            }}
        """)

    def _on_format_changed(self, index):
        """格式选择改变事件"""
        format_name = self.format_combo.currentText()
        
        # 更新选项可用性
        is_video = "视频片段" in format_name
        self.quality_combo.setEnabled(is_video)
        
        # 更新文件扩展名
        if "剪映草稿" in format_name:
            self.path_edit.setText("")
        elif "分镜图片" in format_name:
            self.path_edit.setText("")
        elif "场景列表" in format_name:
            self.path_edit.setText("")
        elif "视频片段" in format_name:
            self.path_edit.setText("")
            
    def _browse_path(self):
        """浏览导出路径"""
        format_name = self.format_combo.currentText()
        
        if "剪映草稿" in format_name:
            file_filter = "剪映草稿文件 (*.draft)"
            default_name = "storyboard.draft"
        elif "分镜图片" in format_name:
            file_filter = "ZIP压缩文件 (*.zip)"
            default_name = "storyboard.zip"
        elif "场景列表" in format_name:
            file_filter = "JSON文件 (*.json)"
            default_name = "scenes.json"
        elif "视频片段" in format_name:
            file_filter = "MP4视频文件 (*.mp4)"
            default_name = "scenes.mp4"
            
        file_path, _ = QFileDialog.getSaveFileName(
            self,
            "选择导出路径",
            default_name,
            file_filter
        )
        
        if file_path:
            self.path_edit.setText(file_path)
            
    def _start_export(self):
        """开始导出"""
        # 检查导出路径
        export_path = self.path_edit.text()
        if not export_path:
            msg = QMessageBox(self)
            msg.setIcon(QMessageBox.Icon.Warning)
            msg.setWindowTitle("警告")
            msg.setText("请选择导出路径")
            msg.setStyleSheet(MESSAGEBOX_STYLE)
            msg.exec()
            return
            
        # 获取导出配置
        config = {
            'format': self.format_combo.currentText(),
            'include_preview': self.include_preview_check.isChecked(),
            'include_metadata': self.include_metadata_check.isChecked(),
            'include_timeline': self.include_timeline_check.isChecked(),
            'video_quality': self.quality_combo.currentText(),
            'export_path': export_path
        }
        
        # 显示进度条
        self.progress_bar.setVisible(True)
        self.progress_bar.setValue(0)
        
        # 禁用导出按钮
        self.export_btn.setEnabled(False)
        
        # 创建导出线程
        self.export_worker = ExportWorker(self.video_path, self.scenes, export_path)
        self.export_worker.progress_updated.connect(self.update_progress)
        self.export_worker.export_finished.connect(self.export_complete)
        self.export_worker.error_occurred.connect(self._on_export_error)
        
        # 发送导出开始信号
        self.export_started.emit(config)
        
        # 启动导出线程
        self.export_worker.start()
        
    def _on_export_error(self, error_msg):
        """处理导出错误"""
        self.progress_bar.setVisible(False)
        self.export_btn.setEnabled(True)
        msg = QMessageBox(self)
        msg.setIcon(QMessageBox.Icon.Critical)
        msg.setWindowTitle("导出错误")
        msg.setText(f"导出过程中发生错误：{error_msg}")
        msg.setStyleSheet(MESSAGEBOX_STYLE)
        msg.exec()
        
    def export_complete(self, file_path):
        """导出完成处理"""
        self.progress_bar.setVisible(False)
        self.export_btn.setEnabled(True)
        self.export_finished.emit(file_path)
        msg = QMessageBox(self)
        msg.setIcon(QMessageBox.Icon.Information)
        msg.setWindowTitle("导出成功")
        msg.setText(f"文件已成功导出到：{file_path}")
        msg.setStyleSheet(MESSAGEBOX_STYLE)
        msg.exec()
        
    def update_progress(self, value):
        """更新进度条"""
        self.progress_bar.setValue(value)

    def _on_export(self):
        """导出剪映草稿工程"""
        if not self.scenes or not self.video_path:
            msg = QMessageBox(self)
            msg.setIcon(QMessageBox.Icon.Warning)
            msg.setWindowTitle("警告")
            msg.setText("请先选择视频和分镜片段")
            msg.setStyleSheet(MESSAGEBOX_STYLE)
            msg.exec()
            return
        
        # 选择导出目录
        from PyQt6.QtWidgets import QFileDialog
        export_dir = QFileDialog.getExistingDirectory(self, "选择导出目录")
        if not export_dir:
            return
        
        # 1. 导出分镜片段到 medias 目录
        medias_dir = os.path.join(export_dir, "medias")
        processor = VideoProcessor()
        processor.load_video(self.video_path)
        exported_files = processor.export_scene_videos(self.scenes, medias_dir)
        
        # 2. 生成 project.json
        materials = []
        timeline = []
        start_time = 0.0
        for i, scene in enumerate(self.scenes):
            material_id = f"scene_{scene.index:03d}"
            rel_path = f"medias/scene_{scene.index:03d}.mp4"
            materials.append({"id": material_id, "path": rel_path})
            timeline.append({
                "material_id": material_id,
                "start": start_time,
                "duration": scene.duration
            })
            start_time += scene.duration
        project_json = {
            "materials": materials,
            "timeline": timeline
        }
        import json
        with open(os.path.join(export_dir, "project.json"), "w", encoding="utf-8") as f:
            json.dump(project_json, f, ensure_ascii=False, indent=2)
        
        msg = QMessageBox(self)
        msg.setIcon(QMessageBox.Icon.Information)
        msg.setWindowTitle("导出成功")
        msg.setText("剪映草稿工程已导出，可直接用剪映导入该目录！")
        msg.setStyleSheet(MESSAGEBOX_STYLE)
        msg.exec()

    def set_scenes(self, scenes, video_path):
        """设置场景数据和视频路径"""
        self.scenes = scenes
        self.video_path = video_path
        # 启用导出按钮
        self.export_btn.setEnabled(True) 